from pymt import *
import os
import gdata.youtube
import gdata.youtube.service
import re
import subprocess
import threading
import random
from OpenGL.GL import *

class MTYouTubeVideoWidget(MTScatterWidget):
  def __init__(self, **kwargs):
    super(MTYouTubeVideoWidget, self).__init__(**kwargs)
    
    self.loading = True
    
    self.uri = kwargs.get('uri')
    #self.uri = "http://www.youtube.com/get_video?video_id=Ih61MJ72v1Y&t=vjVQa1PpcFMj5_pnFKjQj8k9wYUlkNwMeVbc1ay38e4=&eurl=&el=detailpage&ps=default&gl=US&hl=en"
    
    print "MTYouTubeVideoWidget constructed with uri: \'" + self.uri + "\'"
    self.video = MTVideo(filename=self.uri, bordersize=3)#, autostart=True)
    @self.video.event # when the video is downloaded and knows it's size then set the size of the widget to that
    def on_resize(new_width, new_height):
      print "MTYouTubeVideoWidget::on_resize", new_width, new_height
      if(new_width != 0 and new_height != 0):
        self.size = (new_width, new_height)
        self.loading = False
        self.video.visible = True
        
    self.add_widget(self.video)
    self.video.visible = False
   
  def on_draw(self):
    if(self.loading == True):
      #print "Still loading"
      set_color(1, 1, 1, .5)
      drawLabel("Loading", pos=self.pos)
    super(MTYouTubeVideoWidget, self).on_draw()
      
class YoutubeSearch(threading.Thread):
  def __init__(self, caller, keywords, number_of_images):
    super(YoutubeSearch, self).__init__()
    self.connection_timeout = 30 # seconds
    self.connection_time = 0
    self.keywords = keywords
    self.number_of_images = number_of_images
    self.processes = []
    self.caller = caller

  def run(self):
    #print "running"
    self.search(self.keywords)

  def search(self, search_terms):
    print "MTYouTube.search"
    yt_service = gdata.youtube.service.YouTubeService()
    query = gdata.youtube.service.YouTubeVideoQuery()
    query.orderby = 'viewCount'
    query.racy = 'include'
    for search_term in search_terms:
      new_term = search_term.lower() # lower case means keyword means not YouTube category
      query.categories.append('/%s' % new_term)
      feed = yt_service.YouTubeQuery(query)
    for entry in feed.entry[0:self.number_of_images]:
      #print "Entry:", entry.media.player.url
      video_filename = re.match ('(http://www.youtube.com/watch\?v=)(.*)(&feature=youtube_gdata)', entry.media.player.url).group(2)
      self.processes.append(subprocess.Popen(['python', 'youtube-dl', '--get-url', entry.media.player.url], shell=False, stdout=subprocess.PIPE))
    getClock().schedule_interval(self.check_you_tube_videos, 1)

  def check_you_tube_videos(self, delta):
    #print len(self.processes)
    self.connection_time += delta
    #print "Connection time: ", self.connection_time
    if(len(self.processes) == 0 or self.connection_time > self.connection_timeout):
      print "All you tube videos URLs found or timeout"
      
      return False
    for process in self.processes:
      if(process.poll() == 0): # finished
        #print "Process finished"
        (stdout, stderr) = process.communicate()
        #print "stdout = START" + stdout.strip() + "END"
        #self.caller.add_remote_video(stdout[:-2]) # [:-2] removes the newline and carriage return characters returned by stdout (could use .strip())
        #self.caller.add_remote_video(stdout[:-1]) # [:-2] removes the newline and carriage return characters returned by stdout (could use .strip())
        self.caller.add_remote_video(stdout.strip()) # [:-2] removes the newline and carriage return characters returned by stdout (could use .strip())
        self.processes.remove(process)
        

